#define _GNU_SOURCE
#include "../include/head.h"
#include "../include/md5.h"
#define MAX 1000
typedef struct{
    int dataLen;
    char buf[1000];
}Train_t;

int serverGets(int sockFd, int curDirID, int ownerID)
{
    int dataLen = 0;
    int fileSize = 0;
    char fileName[64] = {0};
    char md5str[128] = {0};
    Train_t train;
    memset(&train,0,sizeof(train));
    recv(sockFd,&train.dataLen,4,MSG_WAITALL);
    printf("filename len = %d\n",train.dataLen);
    recv(sockFd,train.buf,train.dataLen,MSG_WAITALL);
    printf("filename is %s\n",train.buf);
    strcpy(fileName,train.buf);
    int fd = open(train.buf,O_RDWR|O_CREAT,0666);
    off_t totalsize;
    
    recv(sockFd,&totalsize,sizeof(off_t),MSG_WAITALL);
    ftruncate(fd,totalsize);
    printf("filesize is %ld\n",totalsize);

    //接收md5码
    recv(sockFd,&train.dataLen,4,MSG_WAITALL);//接收md5码长度
    printf("m5 len is %d\n",train.dataLen);
    recv(sockFd,md5str,train.dataLen,MSG_WAITALL);//接收md5码的内容
    printf("md5 is a %s\n",md5str);
    //查询数据库内有没有md5码匹配，如果用户相同引用计数+1
    //如果用户id不同的md5码匹配到了，就引用计数+1,再插入一条数据进去
    char query[300]="select md5 from file where md5='";
    strcat(query,md5str);
    strcat(query,"'");
    if(selectMd5(query,"1")==1)
    {
        printf("有符合md5码的文件\n");
        char query1[200]="update file set cnt=cnt+1 where md5='";
        strcat(query1,md5str);
        strcat(query1,"'");
        updatePwd(query1);
        
        return 1;
    }
    else
    {
        
        insertNewfile(curDirID, fileName, ownerID, md5str, fileSize, '0');
    }
    char *p =(char*)mmap(NULL,totalsize,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    ERROR_CHECK(p,(char*)MAP_FAILED,"mmap");
    recv(sockFd,p,totalsize,MSG_WAITALL);
    munmap(p,totalsize);
    
    return 0;
}